import router from "../../router";
import store from "../../store";
import utils from "./utils";
import request from "@/common/utils/request.js";
// TODO 路由拦截器
import * as storage from "@/common/utils/storage.js";

import {haveRouters} from '@/router/customizedRouters.js'

import { getUserInfo } from './storage.js'

import {PermissionConfigs, whiteList, defaultOrg_id, envOrg_id} from '@/common/utils/atherUtils.js'

/**
 * routerConfig: 套餐权限,
 * roleConfig: 角色权限,
 * routerKeyInPage: key 对应的页面 name
 */
import { getOnly_digital_human, routerConfig, roleConfig, routerKeyInPage, creativityTools } from '@/common/utils/atherUtils.js'
import { message } from "ant-design-vue";

router.beforeEach(async(to, from, next) => {

  // ["AIdigitalHuman", "SoundCloning", "AIdigitalHumanCreatVideo"]
  // if (
  //   ["SoundCloning"].includes(
  //     to.name
  //   )
  // ) {
  //   // TODO: 临时处理，上线前删除
  //   if (process.env.NODE_ENV == "production") {
  //     const uid = getUserInfo()?.id;
  //     const nextUid = [92645, 92650, 102860];
  //     if (nextUid.includes(uid)) {
  //       next();
  //     } else {
  //       next(false);
  //     }
  //     return;
  //   }
  //   next();
  //   return;
  // }

  // 获取路由
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  let org_id = urlParams.get("org_id") || to?.query?.org_id
  if (org_id) {
    localStorage.setItem("ORG_ID", org_id);
  } else {
    // org_id = utils.getOrgId();

      const config = await store.dispatch("GetConfigInfo")
      console.log(config, 'orgid的confige');
      if (!config?.basic?.can_reg_org) {
        org_id = defaultOrg_id
        } else {
          org_id = (config?.basic?.oem_org_id ??
            config?.basic?.system_org_id) || defaultOrg_id
      }
    
    if (org_id != utils.getOrgId()) {
      store.dispatch("SetOrgId", org_id)
      await store.dispatch("Logout")
    }
  }

  await utils.getUserInfo()
  
  const token = to.query.token || to.query.org_token;
  const source = to.query.source;
  if (!window.__POWERED_BY_QIANKUN__ && window.self === window.top) {
    utils.setDocumentTitle(to.meta.title);
  }

  // 白名单, 随意放行
  if(whiteList.includes(to.name)){
    next()
    return
  }

  // if (to.name == 'mixedCutCreat' || to.name == 'MixedCutPreview') {
      await store.dispatch('Getwork_ai_config')
  // }



  // 判断 是否有权限进入数字人 和声音克隆页面
  const ai_config_control = await goToDigitalAndSound({ to })
  
  if (!ai_config_control) {
    message.error(`您没有权限访问${to.meta?.title}`)
    next(false)
    return 
  }
  
  // 定制数字人路由 并且前往的是不包含在内的路由页面 -  则默认定位到 数字人页面
  const isGo = await goToDigital(to)
  if(!isGo){
    return next({name:'AIdigitalHuman'})
  }

  if (to.name == 'Home' && PermissionConfigs.only_digital_human) {
    return next({name:'AIdigitalHuman'})
  }

  // 判断用户是否拥有权限
  const canGoParam = await canGo({ to, from })
  
  
  if (!canGoParam.is_go && to.name!= 'AIdigitalHuman') {
    message.warning('您暂无权限访问')


    // 如果是完全无权限的页面 - 去往首页
    if (PermissionConfigs.notRedirect) {
      if (to.name != 'Home' && to.path != '/Home') {
        return next("Home")
      } else {
        return next()
      }
    }

    //  return next(false)
    if (canGoParam?.notRedirect) {
      PermissionConfigs.notRedirect = true
    }
    next({ name: canGoParam.redirect })
    return
  }

  trackPageView(to);
  handleTokenAndSource(token, source, to, next);
  if (shouldRedirectToHome(to)) {
    return next({name:'Home'});
  }
});

router.afterEach((to, from) => {
  postMessage(to);
});

function trackPageView(to) {
  if (window._hmt && to.path) {
    window._hmt.push(["_trackPageview", "/#" + to.fullPath]);
  }
}

function shouldRedirectToHome(to) {
  return (
    window.location.origin !== "https://v.kuaijing.cn" &&
    to.path === "/workShotstack"
  );
}

function handleTokenAndSource(token, source, to, next) {

  async function setTokenAndHandleSource() {
    if (token) {
      if (source) {
        handleSource(source);
      }
      await new Promise((resolve) => {
        if (!localStorage.getItem("USER_ACCESS_SOURCE_INFO")) {
          localStorage.setItem(
            "USER_ACCESS_SOURCE_INFO",
            JSON.stringify({
              user_agent: navigator.userAgent,
              source_url: document.referrer,
            })
          );
        }
        next();
        resolve();
      });

      if (shouldRedirectToHome(to)) {
        next({ name: "Home" });
      }else{
        next();
      }
    } else {

      if (PermissionConfigs.only_digital_human && to.name == 'AIdigitalHuman') {
        next()
        return
      }

      if (source) {
        handleSource(source);
      }
      if (shouldRedirectToHome(to)) {
        next({ name: "Home" });
      } else {
        // 开发环境不做判断
        // if (utils.isEnv()) return next()
        // 没有阿里云的权限, 不允许进入一键成片页面
        const shotstack_driver =
          store?.state?.shotstack?.work_ai_config?.shotstack_driver || "";
        if (shotstack_driver != "alionline" && to.name == "OneClickClip") {
          next({ name: "Home" });
          return;
        }
        
        // 没有数字人相关权限  不允许进入数字人相关页面
        const hasVolc = store?.state?.shotstack?.work_ai_config?.hasVolc || false;
                // if (!hasVolc && to.name == "SoundCloning") {
                //   next({ name: "Home" });
                //   return;
                // }
                if (!hasVolc) {
                  next({ name: "Home" });
                  return;
                }
        const hasDigital =
          store?.state?.shotstack?.work_ai_config?.hasDigital || false;
            if (
              !hasDigital &&
              (to.name == "AIdigitalHumanCreatVideo" ||
                to.name == "AIdigitalHuman")
            ) {
              next({ name: "Home" });
              return;
        }
      }
      next()
    }
  }
  setTokenAndHandleSource()

}

function setUserToken(token,next) {
  utils
    .setUserToken(token)
    .then(() => {
      const invite = localStorage.getItem("INVITE_CODE");
      const scene_type = localStorage.getItem("SCENE_TYPE");

      let key
      if (invite) {
        key = scene_type == 2 ? 'agent_code' : 'code'
      }
      const params = {}
      if (key) {
        params[key] = invite
      }
      console.log(111111);
      
      // params
      request
        .get("/work_ai", "/user/info", )
        .then((userResult) => {
          store.commit("SET_TOKEN", userResult.user.user_token);
          store.commit("SET_USER_INFO", userResult.user);
        });
    })
};

function handleSource(source) {
  localStorage.setItem("USER_ACCESS_SOURCE", source);
  if (!localStorage.getItem("USER_ACCESS_SOURCE_INFO")) {
    localStorage.setItem(
      "USER_ACCESS_SOURCE_INFO",
      JSON.stringify({
        user_agent: navigator.userAgent,
        source_url: document.referrer,
      })
    );
  }
}

function postMessage(to) {
  if (!window.__POWERED_BY_QIANKUN__ && window.self !== window.top) {
    window.top.postMessage(
      {
        type: "urlChange",
        title: to.meta.title,
        history: JSON.stringify(window.history.state),
      },
      "*"
    );
  }
}

// 路由过滤 - 判断 是否是定制数字人路由, true - 是  false - 否
const goToDigital = async(to) => {
  PermissionConfigs.only_digital_human = await getOnly_digital_human()
  console.log(PermissionConfigs.only_digital_human,'路由拦截拿到的only_digital_human');
  if(!PermissionConfigs.only_digital_human) return true
  if (!PermissionConfigs.haveArr || (Array.isArray(PermissionConfigs.haveArr) && !PermissionConfigs.haveArr.length)) {
    PermissionConfigs.haveArr = haveRouters()
  }
  if (!PermissionConfigs.haveArr.includes(to.name)) {
    return false
  }
  return true
}

// 一键成片 + 数字人和声音克隆路由过滤
const goToDigitalAndSound = (params = {}) => {
  const {to} = params
  let can_go = true
  const controlsList = ['AIdigitalHuman','AIdigitalHumanCreatVideo', 'SoundCloning', 'OneClickClip' ]
  return new Promise(async (resolve) => {
    // 不是受管理的页面, 不做判断
    if (!controlsList.includes(to.name)) {
      resolve(can_go)
      return
  }
    
    // 开发模式 或未登录 或未正确获取配置参数 不做判断 utils.isEnv() || 
    if (!utils.isLogin()) {
      resolve(can_go)
      return;
    }
    try {
     const configInfo = await store.dispatch("GetConfigInfo")
      const aiConfig = await store.dispatch("Getwork_ai_config")      
     
      if (!Object.keys(aiConfig)) {
        throw new Error('判断条件缺失')
      }
      
      const shotstack_driver = aiConfig.shotstack_driver || ""
      // 判断是否有阿里云的权限, 没有阿里的权限 无法进入一键成片
      if (to.name == 'OneClickClip' && shotstack_driver != "alionline") {
        can_go = false
        resolve(can_go)
        return 
      }
      const hasVolc = aiConfig.hasVolc || false;
      const hasDigital = aiConfig?.hasDigital || false;
  
      // 没有数字人权限, 无法进入创建和数字人页面
      if (!hasDigital && (to.name == 'AIdigitalHuman' || to.name == 'AIdigitalHumanCreatVideo' || to.name == 'AIdigitalHumanMassProduction')) {
        can_go = false
        resolve(can_go)
        return
      }
  
      // 没有声音克隆, 无法进入声音克隆
      if (!hasVolc && to.name == 'SoundCloning') {
        can_go = false
        resolve(can_go)
        return
      }
      resolve(can_go)
    } catch {
      message.error('路由权限获取失败!请重试')
      resolve(false)
    }
   
  })
}

// 过滤拦截 - 根据用户权限 过滤路由 并拦截
const canGo = async (params = {}) => {

  const {to, from} = params

    // 未登录 不做处理
    if (!utils.isLogin() || !storage.getCurrentTeam()) return {
      is_go: true,
      redirect: ''
  }

  // 用户可访问的页面权限
  if (!PermissionConfigs.menus.length) {
    const res = await store.dispatch("getUserTeamDetail");
    PermissionConfigs.power = res?.teamUser?.power??0
    const powerList = res?.teamUser?.team_user_role?.data?? []
    PermissionConfigs.menus = powerList
  }

  if (!PermissionConfigs.roleUser) {
    const Roles = await store.dispatch("GetClipRoleList");
    PermissionConfigs.roleUser = Roles
  }

  // 主创权限
  if (PermissionConfigs.power == 1) {
    // debugger

    let canGoParams = {
      is_go: true,
      redirect:''
    }

    for (let key in routerConfig) {
      const item = routerConfig[key]
      // 如果去的页面是 被套餐权限管理的页面, 并且用户没有该权限
      if (item.includes(to.name) && !PermissionConfigs.roleUser.includes(key)) {
        canGoParams = {
          is_go: false,
          redirect: 'Home'
        }
        break
      } 
    }
    // 去的页面受限, 定位到home
    if(!canGoParams.is_go) {
      return canGoParams 
    }
    return {
      is_go: true,
      redirect: ''
    }
  }

  let is_go = true
  // 普通用户权限判断
  // 第一层判断
  is_go = PermissionConfigs.menus.includes(to.name)
  // 第二层判断: 判断去的是否是某个有权限的页面的子页面
  if (!is_go) {
    for (let key in roleConfig) {
      const item = roleConfig[key]
      if (PermissionConfigs.menus.includes(key) && item.includes(to.name)) {
        is_go = true
        break
      }
    }
  }

  // 第三层判断, 判断是否去的页面是有权限的页面别名
  if (!is_go) {
    for (let key in routerKeyInPage) {
      if (PermissionConfigs.menus.includes(key) && routerKeyInPage[key] == to.name) {
        is_go = true
        break
      }
    }
  }

  // 第四层判断, 判断用户去的是否是创意工具, 如果用户有创意工具下面任意一项权限, 则放行
  if (!is_go && to.name == 'CreativityTools') {
    for (let key in creativityTools) {
      if (PermissionConfigs.menus.includes(key)) {
        is_go = true
        break
      }
    }
  }

  // 第五层判断, 判断用户去的是否是有权限的 创意工具的某一项的子页面
  if (!is_go) {
    // debugger
    for (let key in creativityTools) {
      if (PermissionConfigs.menus.includes(key) && creativityTools[key].includes(to.name)) {
        is_go = true
        break
      }
    } 
  }
  
  // 没有权限, 进行重定向
  if (!is_go) {
    const find = PermissionConfigs.menus.find(ele => ele == 'Home')
    let redirect = find || PermissionConfigs.menus.find(ele => ele!='mbgc') || PermissionConfigs.menus[0]

    // 判断 定向的页面 是否为, 别名页面
    const keys = Object.keys(routerKeyInPage)
    if (keys.includes(redirect)) {
      // 如果是别名, 则重新进行赋值
      redirect = routerKeyInPage[redirect]
    }
    console.log(PermissionConfigs.menus,redirect,'重定向到哪里???');
    // 没有匹配上的定位, 去home页
    if (!redirect) {
      return {
        notRedirect:true,
        redirect: 'Home',
        is_go: false,
      }
    }
    return {
      is_go: false,
      redirect,
    }
  }
  
  // 默认放行
  return {
    is_go: true,
    redirect: '' 
  }
}

